<?php

namespace app\admin\model;

use app\common\command\collect\ConversionAllQuestion;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\facade\Db;
use think\Model;


class Coursequestioncategory extends Model
{


    // 表名
    protected $name = 'course_question_category';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text'
    ];


    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function setQuestionCountById($id, &$processed = [])
    {
        // 检查是否已经处理过该分类，避免循环引用导致的死循环
        if (in_array($id, $processed)) {
            return;
        }
        
        // 将当前分类ID添加到已处理列表
        $processed[] = $id;
        
        // 查询信息
        $row = $this->find($id);
        if (!$row) {
            return;
        }

        // 查询自己分类下试卷总题目数和试卷数量
        $paperModel = new CoursePaper();
        $question_count = $paperModel->where(['category_id' => $id])->sum('question_count');
        $paper_num = $paperModel->where(['category_id' => $id])->count();
        if ($question_count || $paper_num) {
            $this->where(['id' => $id])->update(['question_count' => $question_count, 'paper_num' => $paper_num]);
        }   

        // 查询自己下级分类总题目数和试卷数量
        $question_count = $this->where(['pid' => $id])->sum('question_count');
        $paper_num = $this->where(['pid' => $id])->sum('paper_num');
        if ($question_count || $paper_num) {    
            $this->where(['id' => $id])->update(['question_count' => $question_count, 'paper_num' => $paper_num]);
        }

        // 如果分类不存在上级分类,则退出
        if (!empty($row['pid'])) {
            $this->setQuestionCountById($row['pid'], $processed);
        }
    }

    /*
     * getChildCateId
     */
    public function getChildCateId($cateId, &$processed = []): array
    {
        static $results = [];
        
        // 检查是否已经处理过该分类，避免循环引用导致的死循环
        if (in_array($cateId, $processed)) {
            return $results;
        }
        
        // 将当前分类ID添加到已处理列表
        $processed[] = $cateId;
        
        $allChildCate = $this->where(['pid' => $cateId])->select();
        if ($allChildCate) {
            $results = array_merge($results, array_column((array)$allChildCate, 'id'));
            foreach ($allChildCate as $child) {
                $this->getChildCateId($child['id'], $processed);
            }
        }
        return $results;
    }

    /**
     * updateCateGoryAndPaper
     * @param $course_id
     * @param $cateId
     * @return void
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function updateCateGoryAndPaper($course_id, $cateId)
    {
        $allChildCateId = $this->getChildCateId($cateId);
        $allChildCateId[] = $cateId;

        // 查询所有试卷
        $whereCate = [
            'course_id' => ['=', $course_id],
            'category_id' => ['in', $allChildCateId],
        ];
        $paperModel = new Coursepaper();
        $allPaper = $paperModel->where($whereCate)->select();

        // 计算试卷数量
        $paper_num = count($allPaper);

        // 循环更新试卷的题目数量
        $question_count = 0;
        $questionModel = new Question();
        $allCategoryId = array_column($allPaper, 'category_id');
        foreach ($allPaper as $paper) {
            $where = ['course_id' => $course_id, 'extend_id' => $paper['id']];
            $count = $questionModel->where($where)->count();
            $paperModel->where(['id' => $paper['id']])->update([
                'question_count' => $count
            ]);
            $question_count += $count;
        }

        // 更新分类数据
        foreach ($allCategoryId as $categoryId) {
            $this->setQuestionCountById($categoryId);
        }
    }
}
